<template>
    <div>
        <Tabs 
        type="card" 
        closable 
        v-model="currentTab" 
        @on-tab-remove="removeTab"
        :animated="false" >
            <!-- 账单信息 -->
            <TabPane label="账单信息" :closable="false" :name="'0'">
                <div class="yd-header margin-top-8">
                    <span>账单信息</span>
                    <span>
                        <Button type="primary" @click="getData">数据导出</Button>
                    </span>
                </div>
                <Row :gutter="16" class='flex-style' style='padding-top: 15px;'>
                    <Col span='7'>
                        账单状态
                        <Select
                            v-model="filterData.status"
                            placeholder='不限'
                            clearable
                            class='flex-items'>
                            <Option :value="0">待确定</Option>
                            <Option :value="1">核对争议费用</Option>
                            <Option :value="2">费用未付清</Option>
                            <Option :value="3">已付清</Option>
                            <Option :value="4">已开票</Option>
                        </Select>
                    </Col>
                    <Col span='10'>
                        创建日期
                        <DatePicker 
                        class="flex-items" 
                        placeholder="开始时间" 
                        type="date"
                        @on-change="createStartTimeChange"
                        clearable
                        v-model="filterData.createStartTime"></DatePicker>
                        &nbsp;-&nbsp;
                        <DatePicker 
                        
                        class="flex-items" 
                        placeholder="结束时间" 
                        type="date"
                        @on-change="createEndTimeChange" 
                        clearable
                        v-model="filterData.createEndTime"></DatePicker>
                    </Col>
                    <Col span='7'>
                        结算方式
                        <Select
                            v-model="filterData.contractPaymentType"
                            placeholder='不限'
                            clearable
                            class='flex-items'>
                            <Option :value="1">月结</Option>
                            <Option :value="2">项目制</Option>
                            
                        </Select>
                    </Col>
                </Row>
                <Row :gutter="16" class='flex-style' style='padding: 15px 0;'>
                    <Col span='7'>
                        账单类型
                        <Select
                            v-model="filterData.type"
                            placeholder='不限'
                            clearable
                            class='flex-items'>
                            <Option :value="1">新装账单</Option>
                            <!-- <Option :value="2">项目制</Option> -->
                        </Select>
                    </Col>
                    <Col span='10'>
                        账单月份
                        <DatePicker 
                        class="flex-items" 
                        placeholder="开始时间" 
                        type="date"
                        
                        v-model="filterData.monthBegin"></DatePicker>
                        &nbsp;-&nbsp;
                        <DatePicker 
                        class="flex-items" 
                        placeholder="结束时间" 
                        type="date" 
                        
                        v-model="filterData.monthEnd"></DatePicker>
                    </Col>
                    <Col span='7'>
                        搜索关键字
                        <Input v-model="filterData.keyword" placeholder="请输入关键字"  class="flex-items" />
                        <Button type="primary" style="margin-right:10px" @click="handleSearch">搜索</Button>
                    </Col>
                </Row>
                <Row :gutter="16" class="yd-padding-b-16">
                    <Table stripe border ref="selection" :columns="columns" :data="renters" :loading="isLoadig"></Table>
                </Row>
                <Row>
                    <Page :total="total" 
                    @on-change="getRenterList"
                    :page-size="size" 
                    :current.sync="currentPage"
                    show-elevator 
                    show-total 
                    style="text-align:center"></Page>
                </Row>             
            </TabPane>

            <!-- 账单详情 -->
            <TabPane 
            v-for="(tab,index) in tabs" 
            :name="''+ tab.id" 
            :key="tab.id + index" 
            :label="tab.name" closable>
                <billDetail :id="currentId" :sendModelshow="sendModelshow"></billDetail>
            </TabPane>
            <TabPane label="新增开票" name="contract-add" v-if="contractAddShow">
                <invoiceDetail></invoiceDetail>
            </TabPane>
        </Tabs>

    </div>

    
</template>

<script>
import { http, api } from '@/libs/http'
import billDetail from './billDetail.vue'
import { CountryCodes } from '@/libs/const'
import invoiceDetail from './invoice-detail'
import moment from 'moment'
export default {
  components: {
    billDetail,
    invoiceDetail
  },
  data () {
    return {
      roleId: null,
      CountryCodes,
      client: {}, // 用户
      currentTab: '0', // 当前Tab
      tabs: [],
      start_time: '',
      end_time: '',
      filterData: {},
      contractAddShow: false, // 新建合同显示
      leaseIds: [], // lease_id的数组
      isLoadig: false, // 是否正在发请求
      sendModelshow: false, // 新增回款记录model
      size: 10, // 分页size
      total: 0, // 分页总数
      currentPage: 1,
      searchTypes: [
        {
          value: 1,
          label: '账单执行中'
        },
        {
          value: 2,
          label: '账单已到期'
        },
        {
          value: 3,
          label: '已废除'
        }
      ],
      selectSearchType: 0,
      columns: [
        {
          minWidth: 280,
          align: 'center',
          title: '账单编号',
          key: 'seqno'
        },
        {
          minWidth: 240,
          align: 'center',
          title: '商户',
          key: 'clientName'
        },
        {
          minWidth: 240,
          align: 'center',
          title: '合同名称',
          key: 'contractName'
        },
        {
          minWidth: 240,
          align: 'center',
          title: '账单月份',
          key: 'month'
        },
        {
          minWidth: 240,
          align: 'center',
          title: '账单类型/结算方式',
          render: (h, p) => {
            return [
              <span>{ p.row.typeName + '-' + p.row.contractPaymentTypeName }</span>
            ]
          }
        },
        {
          minWidth: 160,
          title: '覆盖范围',
          align: 'center',
          key: 'contractAreaName'
        },
        {
          minWidth: 140,
          align: 'center',
          title: '总金额',
          key: 'totalCostAmount'
        },
        {
          minWidth: 140,
          align: 'center',
          title: '已收金额',
          key: 'totalPaymentAmount'
        },
        {
          title: '未收金额',
          minWidth: 140,
          align: 'center',
          key: 'totalUnPaymentAmount'
        },
        {
          title: '已开票金额',
          minWidth: 160,
          align: 'center',
          key: 'totalInvoiceAmount'
        },
        {
          title: '账单状态',
          minWidth: 100,
          align: 'center',
          render: (h, p) => <span>{ this.billStatus(p.row.status)}</span>
        },
        {
          title: '云丁商务',
          minWidth: 140,
          align: 'center',
          key: 'principalName'
        },
        {
          title: '账单周期',
          minWidth: 320,
          align: 'center',
          render: (h, p) => <span>{p.row.beginDate + '至' + p.row.endDate}</span>
        },
        {
          title: '创建时间',
          minWidth: 160,
          align: 'center',
          key: 'createTime'
        },
        {
          minWidth: 300,
          align: 'center',
          title: '操作',
          fixed: 'right',
          render: (h, params) => {
            const commonProperty = {
              style: { 'margin-right': '4px' },
              props: { size: 'small' }
            }
            let btn = []
            if (this.roleId === 100) {
              btn = [
                <i-button {...commonProperty} onClick={() => this.handleCheck(params.row)}>查看</i-button>,
                <i-button {...commonProperty} onClick={() => this.contractShow(params.row)}>申请开票</i-button>
              ]
            } else {
              btn = []
            }
            return btn
          }
        }
      ], // 列表结构
      renters: [] // 列表
    }
  },
  created: function () {
    this.filterData.monthBegin = this.getDate()
    this.filterData.monthEnd = new Date()
    if (this.$route.query.renter_id) {
      this.tobillDetail(this.$route.query.renter_id, this.$route.query.renter_name)
    }
    if (this.$route.query.input) {
      this.keyword = this.$route.query.input
    }
    this.getUserInfo()// 列表
  },

  methods: {
    handleCheck (merchant) {
      // 打开新标签显示详情
      let id = '' + merchant.id
      let name = '' + merchant.seqno
      this.toContractDetail(id, name)
    }, // 查看
    toContractDetail (id, name) {
      this.currentId = id
      id = String(id)
      const flag = this.tabs.some(value => {
        return id === value.id
      })

      if (!flag) {
        this.tabs.push({ id, name })
      }
      this.currentTab = id
    }, // 重复标签
    tobillDetail (id, name) {
      id = String(id)

      const flag = this.tabs.some(value => {
        return id === value.id
      })

      if (!flag) {
        this.tabs.push({ id, name })
      }

      this.currentTab = id
    },
    contractShow (row) {
      this.$router.push({
        path: '/fund/invoice_record'
      })
      sessionStorage.setItem('billId', row.id)
    }, // 新建合同显示
    /**
         * 移除tab
         */
    removeTab (name) {
      const pos = this.removeTabDetial(this.tabs, name)
      if (pos) {
        return
      }

      this.removeTabDetial(this.leaseIds, name)
    },

    /**
         * 删除tab具体过程
         * @param {Array} obj
         * @param {String} tabName 关闭的列表名
         * @return {Boolean} true => 表示找到已经删除的tab false => 表示循环完之后依旧没有找到要关闭的tab
         */
    removeTabDetial (arr, tabName) {
      // let { length } = arr;
      for (let i = 0; i < arr.length; i++) {
        const { id } = arr[i]

        if (id === tabName) {
          arr.splice(i, 1)
          return true
        }
      }
      return false
    },
    delRenter (renterId) {
      http.request(this, api.tenant_del, [renterId], null, res => {
        if (res) {
          // 删除成功后刷新
          this.getRenterList(1)
        }
      })
    },

    getRenterList (page) {
      if (this.isLoadig) {
        return
      }
      if (page === 1) {
        this.currentPage = 1
      }

      this.isLoadig = true
      this.filterData.clientId = this.client.clientId
      this.filterData.limit = this.size
      this.filterData.offset = this.size * (page - 1) || 0
      this.filterData.monthBegin = moment(this.filterData.monthBegin).format('YYYY-MM-DD HH:mm:ss')
      this.filterData.monthEnd = moment(this.filterData.monthEnd).format('YYYY-MM-DD HH:mm:ss')
      let query = JSON.parse(JSON.stringify(this.filterData))// 时间必须为date的问题
      query.monthBegin = this.filterData.monthBegin
      query.monthEnd = this.filterData.monthEnd
      http.request(this, api.bill_list, null, query, res => {
        if (res) {
          this.renters = res.rows
          this.total = res.count || 0
        }
        this.isLoadig = false
      })
    },
    dateChange ([start_time, end_time]) {
      this.start_time = start_time
      this.end_time = end_time
    },
    billStatus (val) {
      switch (val) {
        case 0:
          return '待确定'
        case 1:
          return '核对争议费用'
        case 2:
          return '费用未付清'
        case 3:
          return '已付清(全部费用都已已付清)'
        default:
          return '已开票(全部费用都已开票)'
      }
    },
    getData () {
      http.exportTable(this, api.bill_export, null, this.filterData)
    }, // 数据导出
    handleSearch () {
      this.getRenterList(1)
    }, // 搜索
    async getUserInfo () {
      let res = await http.fetch(this, api.user_info, null, null)
      this.roleId = res.role_id
      this.client = {
        clientId: res.client_id,
        clientName: res.client.name
      }
      this.getRenterList(1)
      sessionStorage.setItem('user', JSON.stringify(res))
    }, // 用户信息
    getDate () { // 获取val天前的日期
      let d = new Date()
      // 因为getMonth()获取的月份的值只能在0~11之间所以我们在进行setMonth()之前先给其减一
      d.setMonth((d.getMonth() - 1) - 3)
      let yy1 = d.getFullYear()
      let mm1 = d.getMonth() + 1
      let dd1 = d.getDate()
      if (mm1 < 10) {
        mm1 = '0' + mm1
      }
      if (dd1 < 10) {
        dd1 = '0' + dd1
      }
      return yy1 + '/' + mm1 + '/' + dd1
    },
    createStartTimeChange (val, date) {
      if (!val) return
      this.filterData.createStartTime = moment(this.filterData.createStartTime).format('YYYY-MM-DD HH:mm:ss')
    }, // 开始时间
    createEndTimeChange (val, date) {
      if (!val) return
      this.filterData.createEndTime = moment(this.filterData.createEndTime).format('YYYY-MM-DD HH:mm:ss')
    } // 结束时间
  }
}
</script>

<style lang="less" scoped>
.renter-list {
    &-title {
        height: auto;
    }
    &-hide {
        display: none;
    }
    &-info {
        padding: 5px 0;
    }
    &-save-succ {
        padding: 20px 0;
        text-align: center;
    }
    &-save-succ .icon {
        font-size: 60px;
    }
    &-save-succ span {
        font-size: 20px;
    }
}

.ivu-tabs-tabpane {
    > div {
        visibility: visible !important;
    }
}

.yd-padding-b-16 {
    padding-bottom: 16px;
}
.export-link {
    color: #fff;
    text-decoration: none;
}
.export-link:hover {
    color: #fff;
}
.c-ticket {
    &__search {
        margin: 20px 0;
        padding-bottom: 20px;
        background-color: #efeff1;
        border-bottom: 1px solid #ddd;
    }
    &__row {
        display: flex;
        align-items: center;
    }

    &__label {
        margin-right: 5px;
    }

    &__item {
        flex: 1;
    }

}
.btn{
    margin: 0 0 10px 0
}
.flex-style {
    & > .ivu-col {
        display: flex;
        align-items: center;
        .flex-items {
            flex: 1;
            margin-left: 5px;
        }
    }
}
</style>
